import { Router } from 'express';
import Payload from '../models/Payload';
var models = require('../sqlModels');
let Page = require('../models/Page');
export default () => {
    let api = Router();


    // incomeinfo新增测试
    api.post('/create', async (req, res, next) => {
        let incomeinfoData = req.body;
        try {
        let result = await  models.incomeInfo.create({
                // incomeinfoid: incomeinfoid,
                incomefrom: incomeinfoData.incomefrom,
                incometype: incomeinfoData.incometype,
                incomecount: incomeinfoData.incomecount,
                incomedec: incomeinfoData.incomedec,
                incometime: incomeinfoData.incometime
            })
            res.status(200).json(new Payload(result));
        } catch (error) {
            next(error);
        }
    });

 //获取全部incomeinfo,支持分页
    api.get('/all', async (req, res, next) => {
        try {
            let condition = {
                raw: true
            };
            if (req.query.currentPage && req.query.numPerPage) {
                var numPerPage = parseInt(req.query.numPerPage);
                var currentPage = parseInt(req.query.currentPage);
                condition.offset = numPerPage * (currentPage - 1);
                condition.limit = numPerPage;
            }

            let result = await models.incomeInfo.findAndCountAll(condition);
            let resultLength = result.rows.length;
            let page = new Page(result.rows, currentPage || 1,
                resultLength, numPerPage || resultLength, result.count);
            res.json(new Payload(page));

        } catch (error) {
            next(error);
        }
    })


   //更新incomeInfo
    api.put('/:incomeinfoId', async(req, res, next) => {
        let incomeinfoId = req.params.incomeinfoId;
        let incomeinfoData = req.body;
       try{
           let result = await models.incomeInfo.update({  
                 incomefrom: incomeinfoData.incomefrom,
                incometype: incomeinfoData.incometype,
                incomecount: incomeinfoData.incomecount,
                incomedec: incomeinfoData.incomedec,
                incometime: incomeinfoData.incometime
            }, {
            where: {
                id: incomeinfoId
            }
        })
        res.status(200).json(new Payload(result));
       }catch(error){
           next(error);
       }

    })



//根据ID删除
api.delete('/:incomeinfoId', async(req, res, next) => {
        let incomeinfoId = req.params.incomeinfoId;
       try{
           let result = await models.incomeInfo.destroy({   
                 where: {
                id: incomeinfoId
            }
        })
        res.status(200).json(new Payload(result));
       }catch(error){
           next(error);
       }

    })
    return api;
}
